/*
 * @Description: 
 * @Author: fhw
 * @Date: 2022-11-18 17:23:41
 */
import { Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getPagination, throwHttp } from 'src/utlis';
import { Like, Repository } from 'typeorm';
import { CreateChatGroupDto, DeleteChatGroupDto, GetChatGroupPage, UpdateGroupChatDto, UpdateGroupChatRecordLatestNewsDto } from './dto/group-chat.dto';
import { GroupChat } from './entities/group-chat.entity';
import { ChatUser } from 'src/chat_user/entities/chat_user.entity';
import { HttpExceptionFilter } from 'src/http-exception.filter';
import { isNil } from 'ramda';
import { GroupChatRecord } from 'src/chat-record/entities/group-chat-record.entity';
@Injectable()
export class GroupChatService {
  constructor(
    @InjectRepository(GroupChat)
    private GroupChatRepository: Repository<GroupChat>,
  ) { }
  async getGroupChatPage(params: GetChatGroupPage) {
    try {
      const { pageSize: size, pageNum: num, group_id, groupChatName, managerId } = params
      const { pageSize, pageNum } = getPagination({ pageSize: size, pageNum: num })
      const where = {
        group_id, groupChatName: Like(`%${groupChatName || ''}%`), managerId
      }
      const [data, total] = await this.GroupChatRepository.findAndCount({
        where,
        skip: pageNum * pageSize,
        take: pageSize,
        order: { createDate: 'DESC' },
        cache: true,
      })
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum * pageSize + 1,
      }
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 创建群聊
  @UseFilters(new HttpExceptionFilter())
  async createGroupChat(params: CreateChatGroupDto, { chatUser }: { chatUser: ChatUser; }): Promise<GroupChat> {
    try {
      // 生成随机群聊id
      const groupChat = new GroupChat()
      groupChat.groupChatName = params.name
      groupChat.manager = chatUser
      const result = await this.GroupChatRepository.manager.save(groupChat)
      return result
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 更新群聊信息
  async updateGroupChat(params: UpdateGroupChatDto) {
    try {
      const { manager_id, group_id, announcement, name, group_portrait } = params
      await this.getGroupChatInfo({ managerId: manager_id, group_id })
      const { affected } = await this.GroupChatRepository
        .createQueryBuilder()
        .update('chat_group')
        .set({ announcement, groupChatName: name, group_portrait })
        .where('group_id = :group_id', { group_id })
        .execute()
      if (affected) {
        return '更新成功'
      }
      throwHttp('更新失败')
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 解散群聊
  @UseFilters(new HttpExceptionFilter())
  async deleteGroupChat({ group_id, managerId }: DeleteChatGroupDto) {
    try {
      await this.getGroupChatInfo({ group_id, managerId })
      const { affected } = await this.GroupChatRepository
        .createQueryBuilder()
        .delete().from('chat_group')
        .where('group_id = :group_id', { group_id })
        .execute()
      if (affected) {
        return '成功'
      }
      throwHttp('解散群聊失败')
    } catch (error) {
      throwHttp(error.message)
    }
  }
  /** 获取群聊详情 */
  @UseFilters(new HttpExceptionFilter())
  async getGroupChatInfo(params: DeleteChatGroupDto) {
    try {
      const data = await this.GroupChatRepository.findOne({
        where: params,
        relations: [],
      })
      if (data?.manager) {
        delete data.manager
      }
      if (isNil(data)) {
        throwHttp('当前群聊不存在')
      }
      return data
    } catch (error) {
      throwHttp(error.message)
    }
  }
  /** 更新群聊最新记录 */
  async updateGroupChatRecordLatestNews(params: UpdateGroupChatRecordLatestNewsDto, groupChatRecord: GroupChatRecord) {
    try {
      const { group_id} = params
      await this.getGroupChatInfo({ group_id })
      // // 更新用户
      const data = await this.GroupChatRepository
          .createQueryBuilder()
          .update(GroupChat)
          .set({ latestNewsId: groupChatRecord.id, latestNews: groupChatRecord })
          .where({ group_id })
          .execute();
      if (data.affected) {
          return data
      }
      throwHttp('更新失败')
  } catch (error) {
      throwHttp(error.message)
  }
  }
}
